package com.steven.springbootrabbitmq.controller;

import com.steven.springbootrabbitmq.config.DelayedQueueConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * @author liuxiangyu
 * @date 2021-07-04 22:07
 * 发送延迟消息
 */
@Slf4j
@RestController
@RequestMapping("/ttl")
public class SendMsgController {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    //开始发消息
    @GetMapping("sendMsg/{message}")
    public void sendMsg(@PathVariable String message) {
        log.info("当前时间：{}，发送一条消息给两个TTL队列：{}", new Date().toString(), message);
        rabbitTemplate.convertAndSend("X", "XA", "消息来自ttl为5s的队列：" + message);
        rabbitTemplate.convertAndSend("X", "XB", "消息来自ttl为15s的队列：" + message);
        return;
    }

    //开始发消息和TTL
    @GetMapping("sendExpireMsg/{message}/{ttl}")
    public void sedMsg(@PathVariable String message, @PathVariable String ttl) {
        log.info("当前时间：{}，发送一条时长{}毫秒TTL信息给队列QC:{}", new Date().toString(), ttl, message);
        rabbitTemplate.convertAndSend("X", "XC", message, msg -> {
            //发送消息的延迟时长
            msg.getMessageProperties().setExpiration(ttl);
            return msg;
        });
        return;
    }

    //发送基于插件的延迟消息
    @GetMapping("sendDelayMsg/{message}/{delayTime}")
    public void sendMsg(@PathVariable String message, @PathVariable Integer delayTime) {
        log.info("当前时间：{}，发送一条时长{}毫秒信息给延迟队列delayed.queue:{}",
                new Date().toString(), delayTime, message);
        rabbitTemplate.convertAndSend(
                DelayedQueueConfig.DELAYED_EXCHANGE_NAME,
                DelayedQueueConfig.DELAYED_ROUTING_KEY, message, msg -> {
                    //发送消息的时候，延迟时长
                    msg.getMessageProperties().setDelay(delayTime);
                    return msg;
                });
        return;
    }
}
